package com.psp.sp.service.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.northend.util.AppTextUtil;
import com.northend.util.DateUtil;
import com.northend.util.MD5Util;
import com.northend.util.NumUtil;
import com.northend.util.RandomUtil;
import com.northend.util.StringUtil;
import com.northend.util.VCodeSender;
import com.psp.sp.cache.dao.UserCacheDao;
import com.psp.sp.constants.ConfigConstants;
import com.psp.sp.constants.StringConstants;
import com.psp.sp.model.Code;
import com.psp.sp.model.UserBean;
import com.psp.sp.persist.dao.UserDao;
import com.psp.sp.service.UserService;
import com.psp.sp.service.exception.ServiceException;
import com.psp.sp.util.mail.MailSendUtil;

@Service
public class UserServiceImpl implements UserService {
	Logger logger = Logger.getLogger(UserServiceImpl.class);
	@Autowired
	UserDao userImpl;
	@Autowired
	UserCacheDao userCacheImpl;

	VCodeSender phoneCode = VCodeSender.getInstance("N1330628", "t7NYh90uB");

	public UserBean regByPhone(String sessionId, String phone, String pwd, String confirmPwd, String vcode,
			String device, String imgCode) {
		checkImgCode(phone, imgCode);

		String code = userCacheImpl.getVCode(1, phone);
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}
		logger.info("phone is:" + phone + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code)) {
			throw new ServiceException("vcode_is_error");
		}
		UserBean user = userImpl.selectOneByPhone(phone);
		if (user != null) {
			throw new ServiceException("object_is_exist", new Object[] { "用户" });
		}
		if (!pwd.equals(confirmPwd)) {
			throw new ServiceException("user_password_is_not_same");
		}
		UserBean newuser = new UserBean();
		newuser.setUid(AppTextUtil.getPrimaryKey());
		newuser.setPhone(phone);
		newuser.setPassword(MD5Util.sha256Hex(pwd));
		newuser.setDevice(device);
		newuser.setState(Integer.valueOf(1));

		boolean flag = userImpl.insert(newuser) == 1;

		logger.info("new User is:" + newuser);
		if (flag) {
			userCacheImpl.setUserSession(sessionId, newuser.getUid(), 86400L);

			return newuser;
		}
		return null;
	}

	public UserBean regByEmail(String sessionId, String email, String pwd, String confirmPwd, String device,
			String imgCode) {
		checkImgCode(email, imgCode);

		UserBean user = userImpl.selectOneByEmail(email);
		if (user != null) {
			throw new ServiceException("object_is_exist", new Object[] { "用户" });
		}
		if (!pwd.equals(confirmPwd)) {
			throw new ServiceException("user_password_is_not_same");
		}
		UserBean newuser = new UserBean();
		newuser.setUid(AppTextUtil.getPrimaryKey());
		newuser.setEmail(email);
		newuser.setPassword(MD5Util.sha256Hex(pwd));
		newuser.setDevice(device);
		newuser.setState(Integer.valueOf(2));

		boolean flag = userImpl.insert(newuser) == 1;

		logger.info("new User is:" + newuser);
		if (flag) {
			userCacheImpl.setUserSession(sessionId, newuser.getUid(), 86400L);

			return newuser;
		}
		return null;
	}

	public UserBean existUser(int type, String username) {
		UserBean user = null;
		if (StringUtil.isMobileNO(username)) {
			user = userImpl.selectOneByPhone(username);
		} else if (StringUtil.isEmail(username)) {
			user = userImpl.selectOneByEmail(username);
		}
		if (type == 1) {
			if (user == null) {
				throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
			}
		} else if ((type == 2) && (user != null)) {
			throw new ServiceException("object_is_exist", new Object[] { "用户" });
		}
		return user;
	}

	public UserBean existUser(String sessionId) {
		String uid = userCacheImpl.getUidBySession(sessionId);
		if (uid == null) {
			return null;
		}
		return userImpl.selectOne(uid);
	}

	public boolean sendVCode(String icode, int type, String phone) {
		UserBean user = userImpl.selectOneByPhone(phone);
		if (type == 1 && user != null) {// 1 绑定手机号，2 更新手机号,3 找回密码
			throw new ServiceException("object_is_exist", new Object[] { "手机号" });
		} else if (type == 2 | type == 3) {
			if (user == null)
				throw new ServiceException("object_is_not_exist", new Object[] { "手机号" });
		}
		checkImgCode(phone, icode);
		String vcode = RandomUtil.getRandomNum(4);
		logger.info("the phone vcode is : " + vcode);

		userCacheImpl.setVCode(type, phone, vcode);
		String c = userCacheImpl.getVCode(type, phone);
		logger.info("vcode is : " + c);

		String msg = StringConstants.getInstance().getString("msg_vcode_test", new Object[] { vcode });
		phoneCode.send(phone, msg, null);
		return true;
	}

	private void checkImgCode(String userName, String i) {
		Code imgCode = userCacheImpl.getImgCode(userName);
		logger.info("the imgcode is : " + imgCode);
		if (imgCode == null) {
			throw new ServiceException("imgcode_is_expire");
		}
		if ((StringUtil.isEmpty(i)) || (!i.equals(imgCode.getCode()))) {
			logger.info("set imgcode is : " + imgCode);
			throw new ServiceException("imgcode_is_error");
		}
	}

	public boolean sendActivateEmail(String email) {
		if (!StringUtil.isEmail(email)) {
			throw new ServiceException("param_is_error", new Object[] { "邮箱" });
		}
		UserBean user = userImpl.selectOneByEmail(email);
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		String verifyCode = userCacheImpl.getEmailCodeByUid(user.getUid());
		if (verifyCode == null) {
			verifyCode = AppTextUtil.getFileKey();
		}
		StringBuffer emailbuffer = new StringBuffer();
		String path = ConfigConstants.getInstance().getPath("webPath");
		emailbuffer.append(
				"<table style='border-collapse: collapse; border-spacing: 0; font: 18px/34px 'Microsoft Yahei', Tahoma; text-align: left;'>");
		emailbuffer.append(
				"<thead>\t\t\t<tr style='border-bottom: 1px solid #ccc;'>\t\t\t\t<th style='padding: 10px 40px;' align='left'>");
		emailbuffer.append(
				"<img src=\"http://47.93.144.246/psp-web/img/logo-oneplus.png\" alt=\"公共服务平台\"></th></tr></thead>\t");
		emailbuffer.append(
				"<tbody><tr><td style=\"padding: 0 40px;\"><p style=\"margin-top: 20px;\"亲爱的用户：<br> 您好！<br> 您于");
		String now = DateUtil.getDate(null);
		emailbuffer.append(now + "申请注册公共服务平台账号" + email + "<br>");
		emailbuffer.append("点击下方激活链接即可完成注册：</p>");
		emailbuffer.append("<p style=\"line-height: 28px; margin-top: 30px;\"><a href=\"http://" + path
				+ "/psp-web/psp/user/v1/activateEmail?activateCode=" + verifyCode
				+ "\" target=\"_blank\" style=\"text-decoration: underline; color: #39c;\">");
		emailbuffer.append(
				"http://" + path + "/psp-web/psp/user/v1/activateEmail?activateCode=" + verifyCode + "</a></p>");
		emailbuffer.append("<span style=\"font-size: 12px; color: #999;\">如果您无法点击此链接，请将它复制到浏览器地址栏后访问</span>");
		emailbuffer.append("<p style=\"line-height: 25px; font-size: 14px; margin-top: 20px;\">");
		emailbuffer.append("1.为了保障您账号的安全性，请在24小时内完成激活，此链接将在您激活过一次后失效！<br>");
		emailbuffer.append("2.请尽快完成激活，否则链接将过期，中关村公共服务平台将有权于24小时后收回账号；<br>");
		emailbuffer.append("3.本邮件由中关村公共服务平台官网系统自动发出，请勿直接回复！<br>");
		emailbuffer.append("4.如果您有任何疑问或建议，请随时拨打中关村公共服务平台客服热线：400-888-1111</p></p></td></tr>\t</tbody></table><br><br>");
		String theme = "您已创建公共服务平台账号，请激活";
		boolean flag = MailSendUtil.sendMail(email, theme, emailbuffer.toString());
		if (flag) {
			userCacheImpl.setEmailCode(user.getUid(), verifyCode);
			return flag;
		}
		return false;
	}

	public boolean activateEmail(String code) {
		String userId = userCacheImpl.getUidByEmailCode(code);
		if (userId == null) {
			throw new ServiceException("vcode_is_expire");
		}
		UserBean user = userImpl.selectOne(userId);
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		int state = user.getState().intValue();
		if (state == 1) {
			throw new ServiceException("user_is_actived");
		}
		return userImpl.updateState(userId, 1) > 0;
	}

	public UserBean login(String sessionId, String userName, String pwd, String vcode) {
		UserBean user = null;
		if (StringUtil.isMobileNO(userName)) {
			user = userImpl.selectOneByPhone(userName);
		} else if (StringUtil.isEmail(userName)) {
			user = userImpl.selectOneByEmail(userName);
		}
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		logger.info("login user is : " + user);

		Code code = userCacheImpl.getLoginCode(user.getUid());
		logger.info("first code is : " + code);
		if (code == null) {
			code = new Code();
			code.setNum(0);
			userCacheImpl.setLoginCode(user.getUid(), code);
		}
		logger.info("set code is : " + code);
		pwd = MD5Util.sha256Hex(pwd);
		if (!pwd.equals(user.getPassword())) {
			code.setNum(code.getNum() + 1);
			userCacheImpl.setLoginCode(user.getUid(), code);
			throw new ServiceException("user_password_is_error");
		}
		if ((code.getNum() > 5) && ((StringUtil.isEmpty(vcode)) || (!vcode.equals(code.getCode())))) {
			throw new ServiceException("vcode_is_error");
		}
		logger.info("get code is : " + userCacheImpl.getLoginCode(user.getUid()));
		if (NumUtil.toInt(user.getState(), 0) == 2) {
			throw new ServiceException("user_is_not_active");
		}
		userCacheImpl.setUserSession(sessionId, user.getUid(), 86400L);
		boolean flag = userImpl.updateLoginTime() > 0;
		// TODO:登录日志

		return user;
	}

	public UserBean getUser(String userId) {
		return userImpl.selectOne(userId);
	}

	@Override
	public boolean updateUser(String userId, String name, String idNo, String headerIcon, int gender) {
		UserBean user = userImpl.selectOne(userId);
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		user.setGender(gender);
		user.setUserName(name);
		user.setIdno(idNo);
		user.setHeadIcon(headerIcon);

		return userImpl.updateUser(user) > 0;
	}

	@Override
	public UserBean sendFindPwdCode(String userName, String code) {
		UserBean user = userImpl.selectOneByPhone(userName);
		if (user == null)
			throw new ServiceException("object_is_not_exist", new Object[] { "未注册，手机号" });
		checkImgCode(userName, code);
		String vcode = RandomUtil.getRandomNum(4);
		logger.info("the phone vcode is : " + vcode);

		userCacheImpl.setVCode(3, userName, vcode);
		String c = userCacheImpl.getVCode(3, userName);
		logger.info("vcode is : " + c);

		if (StringUtil.isMobileNO(userName)) {// 手机发送短信验证码
			String msg = StringConstants.getInstance().getString("msg_vcode_test", new Object[] { vcode });
			phoneCode.send(userName, msg, null);

		} else if (StringUtil.isEmail(userName)) {
			StringBuffer emailbuffer = new StringBuffer();
			emailbuffer.append(
					"<table style='border-collapse: collapse; border-spacing: 0; font: 18px/34px 'Microsoft Yahei', Tahoma; text-align: left;'>");
			emailbuffer.append(
					"<thead>\t\t\t<tr style='border-bottom: 1px solid #ccc;'>\t\t\t\t<th style='padding: 10px 40px;' align='left'>");
			emailbuffer.append(
					"<img src=\"http://47.93.144.246/psp-web/img/logo-oneplus.png\" alt=\"公共服务平台\"></th></tr></thead>\t");
			emailbuffer.append(
					"<tbody><tr><td style=\"padding: 0 40px;\"><p style=\"margin-top: 20px;\"亲爱的用户：<br> 您好！<br> 您于");
			String now = DateUtil.getDate(null);
			emailbuffer.append(now + "申请重置公共服务平台账号密码" + userName + "<br>");
			emailbuffer.append("验证码为：</p>");
			emailbuffer.append("<p style=\"line-height: 28px; margin-top: 30px;\">" + vcode + "</p>");
			emailbuffer.append("<p style=\"line-height: 25px; font-size: 14px; margin-top: 20px;\">");
			emailbuffer.append("1.为了保障您账号的安全性，请在10分钟内完成密码重置,10分钟后失效！<br>");
			emailbuffer.append("2.本邮件由中关村公共服务平台官网系统自动发出，请勿直接回复！<br>");
			emailbuffer.append(
					"3.如果您有任何疑问或建议，请随时拨打中关村公共服务平台客服热线：400-888-1111</p></p></td></tr>\t</tbody></table><br><br>");
			String theme = "您申请重置公共服务平台账号密码的验证码";
			boolean flag = MailSendUtil.sendMail(userName, theme, emailbuffer.toString());
			if (flag) {
				userCacheImpl.setVCode(3, userName, vcode);
			}
		}

		return user;
	}

	@Override
	public UserBean confirmFindPwdCode(String account, String vcode) {

		String code = userCacheImpl.getVCode(3, account);// 1 绑定手机号，2 更新手机号,3
															// 找回密码
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}
		logger.info("account is:" + account + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code)) {
			throw new ServiceException("vcode_is_error");
		}
		UserBean user = new UserBean();
		if (StringUtil.isMobileNO(account)) {// 手机发送短信验证码
			user.setPhone(account);
		} else if (StringUtil.isEmail(account)) {
			user.setEmail(account);
		}
		return user;
	}

	@Override
	public boolean resetPwd(String account, String vcode, String pwd, String confirmPwd) {

		String code = userCacheImpl.getVCode(3, account);// 1 绑定手机号，2 更新手机号,3
															// 找回密码
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}
		logger.info("account is:" + account + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code)) {
			throw new ServiceException("vcode_is_error");
		}

		UserBean user = null;
		if (StringUtil.isMobileNO(account)) {// 手机
			user = userImpl.selectOneByPhone(account);
		} else if (StringUtil.isEmail(account)) {// 邮箱
			user = userImpl.selectOneByEmail(account);
		}
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		if (!pwd.equals(confirmPwd)) {
			throw new ServiceException("user_password_is_not_same");
		}
		user.setPassword(MD5Util.sha256Hex(pwd));

		return userImpl.updatepwd(user) > 0;
	}

	@Override
	public boolean apply(String userId) {
		UserBean user = userImpl.selectOne(userId);
		// user.setState(3);// 3申請狀態
		return userImpl.updateState(userId, 3) > 0;
	}
}
